import { _decorator, Component, EventKeyboard, EventTouch, Input, input, KeyCode } from 'cc';
import { directionType } from './Util';
const { ccclass } = _decorator;

@ccclass('InputManager')
export class InputManager extends Component {
    start() {

    }

    update(deltaTime: number) {
        
    }

    protected onEnable(): void {
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
    }

    protected onDisable(): void {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
    }

    onKeyDown(event: EventKeyboard) {
        switch (event.keyCode) {
            case KeyCode.ARROW_UP:
            case KeyCode.KEY_W:
                this.node.emit('move', directionType.up);
                break;
            case KeyCode.ARROW_DOWN:
            case KeyCode.KEY_S:
                this.node.emit('move', directionType.down);
                break;
            case KeyCode.ARROW_LEFT:
            case KeyCode.KEY_A:
                this.node.emit('move', directionType.left);
                break;
            case KeyCode.ARROW_RIGHT:
            case KeyCode.KEY_D:
                this.node.emit('move', directionType.right);
                break;
        }
    }

    private onTouchMove(event: EventTouch) {
        const delta = event.getDelta();
        // 短距离滑动 不做处理
        if (Math.abs(delta.x) < 12 && Math.abs(delta.y) < 12) {
            return;
        }
        if (Math.abs(delta.x) > Math.abs(delta.y)) {
            if (delta.x > 0) {
                this.node.emit('move', directionType.right);
            } else {
                this.node.emit('move', directionType.left);
            }
        } else {
            if (delta.y > 0) { 
                this.node.emit('move', directionType.up);
            } else {
                this.node.emit('move', directionType.down);
            }
        }
    }
}


